//
//  UserManagerV2.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/11/11.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "UserManagerV2.h"

#import "CommonMsgData.h"

@interface UserManagerV2()

@property (nonatomic, readwrite, assign) BOOL isNeedUpdate;

@property (nonatomic, readwrite, strong) UserInfoData* userData;
@property (nonatomic, readwrite, strong) UserDetailData* userDetailData;
@property (nonatomic, readwrite, strong) ExpertDetailInfoData* expertData;
@property (nonatomic, readwrite, strong) EnterpriseDetailInfoData* enterpriseData;
@property (nonatomic, readwrite, strong) InstitutionDetailInfoData* institutionData;
@property (nonatomic, readwrite, strong) UserCenterInfoData* userCenterInfoData;

@property (nonatomic, readwrite, copy) NSString* userToken;

@property (nonatomic, readwrite, assign) NSInteger unReadMsgNum;

@property (nonatomic, readwrite, strong) RACCommand* cleanUnReadMsgCmd;

@end

@implementation UserManagerV2

MHSingletonM(UserManagerV2);

NSString* UM_appLanguageV2 = @"CH";

//+ (void)checkUserToken:(VoidBlock_id)block
//{
//    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
//    NSString* strUserToken = [userDefaults objectForKey:@"UserToken"];
//
//    if ([strUserToken isNotBlank])
//    {
//        @weakify(self)
//        /// 发起请求
//        [[AFNetWorkUtils racPOSTWthURL:url_interface_userMessage params:[NSString dic2url:interface_param_userMessage(strUserToken)]] subscribeNext:^(id x) {
//            //成功返回(result class is NSDictionary)
//
//            @strongify(self);
//            HDUser* hdLogin = [HDUser modelWithJSON:x[@"result"]];
//
//            block(@YES);
//
//        } error:^(NSError *error) {
//            //错误处理
//
//            [userDefaults setObject:@"" forKey:@"UserToken"];
//            [userDefaults synchronize];
//
//            block(@NO);
//        }];
//    }
//    else
//    {
//        block(@NO);
//    }
//}

- (id)init
{
    self = [super init];
    
    if (self)
    {
        [self reset];
        [self initUserConfig];
        [self initRAC];
    }
    
    return self;
}

- (void)reset
{
    _userData = nil;
    _userToken = @"";
    _unReadMsgNum = 0;
}

- (void)initUserConfig
{
    //是否有已登录
    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
    //    strUserToken = @"619DB322B2F7B9365C31FC9774FF2FA7";
    //    strUserToken = @"348802CEEE3E15CEE0C1CDCA1E0F8086";
    self.userToken = [userDefaults objectForKey:@"UserToken"];
    
    _isNeedUpdate = NO;
}

- (void)initRAC
{
    @weakify(self)
    
    DataManager* dm = [DataManager sharedDataManager];
    
    self.cleanUnReadMsgCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
                              {
                                  @strongify(self);
                                  
                                  return [self requestCleanUnReadMsgSignal];
                              }];
    
#pragma mark -- 用户信息
//    RACSignal* userDataChangeSignal = [[RACObserve(self, userData) distinctUntilChanged] replay];
//
//    [[userDataChangeSignal skip:1] subscribeNext:^(id x)
//     {
//         @strongify(self);
//
//         UserInfoData* curUserData = x;
//
//         self.userToken = curUserData!=nil?curUserData.userID:@"";
//     }];
    
#pragma mark -- 用户token改变
    RACSignal* userTokenChangeSignal = [[RACObserve(self, userToken) distinctUntilChanged] replay];
    
    [[[[[[userTokenChangeSignal doNext:^(id x)
        {
            @strongify(self)
            
            NSString* curUserToken = x;
            
            NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:curUserToken forKey:@"UserToken"];
            [userDefaults synchronize];
        }] filter:^BOOL(id value) {
            @strongify(self)
            
            return [self.userToken isNotBlank];
        }] flattenMap:^RACStream *(id value) {
            
            @strongify(self)
            
            return [self requestUnReadMsgSignal];
        }] initially:^{
            if (dm.isLoadingOver)
                [MBProgressHUD mh_showProgressHUD:@"更新用户信息..."];
        }] finally:^{
            if (dm.isLoadingOver)
                [MBProgressHUD mh_hideHUD];
        }] subscribeNext:^(id x)
        {
            @strongify(self);
            
            [self updateUserInfo];
        }];
    
    RACSignal* updateSignal = [[[[RACObserve(self, isNeedUpdate) distinctUntilChanged] filter:^BOOL(id value)
    {
        @strongify(self)
        
        return [value boolValue] && [self.userToken isNotBlank];
    }] map:^id(id value)
    {
        @strongify(self);
        
        return self.userToken;
    }] replay];
    
    RACSignal* mergeSignal = [RACSignal merge:@[updateSignal]];
    [[mergeSignal flattenMap:^RACStream *(id value) {
        @strongify(self);
        
        @weakify(self);
        return [[[[[self requestUserInfoSignal] filter:^BOOL(id value2) {
            if ([value2 boolValue])
            {
                NSLog(@"用户信息获取成功");
            }
            else
            {
                NSLog(@"用户信息获取失败");
            }
            
            return [value2 boolValue];
        }] flattenMap:^RACStream *(id value)
        {
            @strongify(self);
            
            return [self _requestUserDetailSignal];
        }] flattenMap:^RACStream *(id value)
        {
            @strongify(self);
             
            return [self _requestUserCenterInfoSignal];
        }] flattenMap:^RACStream *(id value)
        {
            @strongify(self);
            
            if ([self.userData.identify integerValue] > 1)
            {
                return [self requestSpInfoSignal];
            }
            else
            {
                return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                    [subscriber sendNext:nil];
                    [subscriber sendCompleted];
                    
                    return nil;
                }];
            }
        }];
    }] subscribeNext:^(id x) {
        
        @strongify(self)
        self.isNeedUpdate = NO;
        
        [self userDataRefresh];
    }];
    
#pragma mark -- 未读消息
    [[RACObserve(self, unReadMsgNum) deliverOnMainThread] subscribeNext:^(id x) {
        @strongify(self);
        
        [[NSNotificationCenter defaultCenter] postNotificationName:Notify_Tabbar_BadgeNum object:@{@"ShowIndex":@1, @"BadgeNum":@(self.unReadMsgNum)}];
    }];
    
#pragma mark -- 支付推送
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:Notify_Pay_Push object:nil]
      filter:^BOOL(id value)
      {
          @strongify(self);
          
          return [self isLogined];
      }] subscribeNext:^(id x)
     {
         @strongify(self);
         
         [self updateUserInfo];
     }];
}

- (void)clean
{
    self.userData = nil;
    self.userToken = @"";
    self.userDetailData = nil;
    self.expertData = nil;
    self.enterpriseData = nil;
    self.institutionData = nil;
    self.userCenterInfoData = nil;
    
    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:@"" forKey:@"UserToken"];
    [userDefaults synchronize];
}

- (BOOL)isLogined
{
    return _userData!=nil && [_userData.userID isNotBlank];
}

- (void)updateUserToken:(NSString*)userID
{
    self.userToken = @"";
    self.userToken = userID;
}

- (BOOL)isHaveUserToken
{
    return [self.userToken isNotBlank];
}

- (void)logonOut
{
    //    [self userUnBindDevToken];
    
    if (self.userData)
    {
        [[UMManager sharedUMManager] removeAlias:_userData.userID];
    }
    
    [self clean];
    
    DataManager* dataMgr = [DataManager sharedDataManager];
    [dataMgr cleanDBMgr];
    
    [self userDataRefresh];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:Notify_Logout object:nil];
}

- (void)saveUserData:(UserInfoData*)userData
{
    self.userData = userData;
    
    NSString* dbName = HCStrFormat(@"%@.sqlite", self.userData.userID);
    DataManager* dataMgr = [DataManager sharedDataManager];
    [dataMgr createDBMgr:dbName];
    
    [[UMManager sharedUMManager] bindAlias:self.userData.userID];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:Notify_LoginSuc object:nil];
}

- (void)updateUserInfo
{
    self.isNeedUpdate = NO;
    self.isNeedUpdate = YES;
}

- (void)cleanUnReadMsg
{
    [self.cleanUnReadMsgCmd execute:nil];
}

- (void)userDataRefresh
{
    NSLog(@"UserDataRefreshing!!!!");
}

#pragma mark - Signal
- (RACSignal*)_requestUserDetailSignal
{
    @weakify(self);
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                @strongify(self);
                
                @weakify(self);
                [[AFNetWorkUtils racPOSTWthURL:url_interface_userdetail params:interface_param_userdetail(self.userData.userID)] subscribeNext:^(id x)
                 {
                     @strongify(self);
                     
                     UserDetailData* userDetailData = [UserDetailData modelWithJSON:x];
                     
                     self.userDetailData = userDetailData;
                     
                     NSLog(@"UserDetailData - Finish");
                     
                     [subscriber sendNext:@YES];
                     [subscriber sendCompleted];
                 } error:^(NSError *error)
                 {
                     [subscriber sendNext:@NO];
                     [subscriber sendCompleted];
                 }];
                
                return nil;
            }];
}

- (RACSignal*)_requestUserCenterInfoSignal
{
    @weakify(self);
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                @strongify(self);
                
                @weakify(self);
                [[AFNetWorkUtils racPOSTWthURL:url_interface_usertop params:interface_param_usertop(self.userData.userID)] subscribeNext:^(id x)
                 {
                     @strongify(self);
                     
                     UserCenterInfoData* ucInfoData = [UserCenterInfoData modelWithJSON:x];
                     
                     self.userCenterInfoData = ucInfoData;
                     
                     NSLog(@"UserCenterData - Finish");
                     
                     [subscriber sendNext:@YES];
                     [subscriber sendCompleted];
                 } error:^(NSError *error)
                 {
                     [subscriber sendNext:@NO];
                     [subscriber sendCompleted];
                 }];
                
                return nil;
            }];
}

- (RACSignal*)requestUnReadMsgSignal
{
    @weakify(self)
    
    //TODO: 暂时无接口
    if (true|| ![self isHaveUserToken])
    {
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            
            [subscriber sendNext:nil];
            [subscriber sendCompleted];
            
            return nil;
        }];
    }
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                @strongify(self)
                
                @weakify(self);
                NSString* strParam = interface_param_getusermessages(0);
                NSString* strReqUrl = HCStrFormat(@"%@%@", url_interface_getusermessages, strParam);
                [[AFNetWorkUtils racGETWthURL:strReqUrl] subscribeNext:^(id x)
                 {
                     @strongify(self)
                     
                     CommonMsgData* comMsgData = [CommonMsgData modelWithJSON:x];
                     
                     self.unReadMsgNum = comMsgData.totalcount;
                     
                     [subscriber sendNext:@YES];
                     [subscriber sendCompleted];
                 }  error:^(NSError *error) {
                     //错误处理
                     
                     [subscriber sendNext:@NO];
                     [subscriber sendCompleted];
                 }];
                
                return nil;
            }];
}

- (RACSignal*)requestCleanUnReadMsgSignal
{
    @weakify(self)
    
    if (![self isHaveUserToken])
    {
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            
            [subscriber sendNext:nil];
            [subscriber sendCompleted];
            
            return nil;
        }];
    }
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                @strongify(self)
                
                @weakify(self);
                [[AFNetWorkUtils racGETWthURL:url_interface_readusermessages] subscribeNext:^(id x)
                 {
                     @strongify(self)
                     
                     self.unReadMsgNum = 0;
                     
                     [subscriber sendNext:@YES];
                     [subscriber sendCompleted];
                 }  error:^(NSError *error) {
                     //错误处理
                     
                     [subscriber sendNext:@NO];
                     [subscriber sendCompleted];
                 }];
                
                return nil;
            }];
}

- (RACSignal*)requestUserInfoSignal
{
    @weakify(self)
    
    if (![self isHaveUserToken])
    {
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            
            [subscriber sendNext:nil];
            [subscriber sendCompleted];
            
            return nil;
        }];
    }
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                @strongify(self);
                
                NSString* strUserID = self.userToken;
                
                @weakify(self);
                [[AFNetWorkUtils racPOSTWthURL:url_interface_userInfo params:interface_param_userInfo(strUserID)] subscribeNext:^(id x)
                 {
                     @strongify(self)
                     
                     UserInfoData* userData = [UserInfoData modelWithJSON:x];
                     
                     [self saveUserData:userData];
                     
                     NSLog(@"UserInfoSignal - Finish");
                     
                     [subscriber sendNext:@YES];
                     [subscriber sendCompleted];
                 }  error:^(NSError *error) {
                     //错误处理
                     
                     [subscriber sendNext:@NO];
                     [subscriber sendCompleted];
                 }];
                
                return nil;
            }];
}

- (RACSignal*)requestSpInfoSignal
{
    @weakify(self)
    
    if (![self isHaveUserToken])
    {
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            
            [subscriber sendNext:nil];
            [subscriber sendCompleted];
            
            return nil;
        }];
    }
    
    NSInteger identify = [self.userData.identify integerValue];
    
    //专家
    if (identify == 2)
    {
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
                {
                    @strongify(self);
                    
                    NSString* strUserID = self.userToken;
                    
                    @weakify(self);
                    [[AFNetWorkUtils racPOSTWthURL:url_interface_expertInfo params:interface_param_expertInfo(strUserID)] subscribeNext:^(id x)
                     {
                         @strongify(self)
                         
                         ExpertDetailInfoData* expertDetailInfo = [ExpertDetailInfoData modelWithJSON:x];
                         
                         self.expertData = expertDetailInfo;
                         
                         NSLog(@"ExpertInfoSignal - Finish");
                         
                         [subscriber sendNext:@YES];
                         [subscriber sendCompleted];
                     }  error:^(NSError *error) {
                         //错误处理
                         
                         [subscriber sendNext:@NO];
                         [subscriber sendCompleted];
                     }];
                    
                    return nil;
                }];
    }
    // 企业
    else if (identify == 3)
    {
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
                {
                    @strongify(self);
                    
                    NSString* strUserID = self.userToken;
                    
                    @weakify(self);
                    [[AFNetWorkUtils racPOSTWthURL:url_interface_enterpriseInfo params:interface_param_enterpriseInfo(strUserID)] subscribeNext:^(id x)
                     {
                         @strongify(self)
                         
                         EnterpriseDetailInfoData* detailInfo = [EnterpriseDetailInfoData modelWithJSON:x];
                         
                         self.enterpriseData = detailInfo;
                         
                         NSLog(@"UserInfoSignal - Finish");
                         
                         [subscriber sendNext:@YES];
                         [subscriber sendCompleted];
                     }  error:^(NSError *error) {
                         //错误处理
                         
                         [subscriber sendNext:@NO];
                         [subscriber sendCompleted];
                     }];
                    
                    return nil;
                }];
    }
    else if (identify == 4)
    {
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
                {
                    @strongify(self);
                    
                    NSString* strUserID = self.userToken;
                    
                    @weakify(self);
                    [[AFNetWorkUtils racPOSTWthURL:url_interface_institutionnfo params:interface_param_institutionnfo(strUserID)] subscribeNext:^(id x)
                     {
                         @strongify(self)
                         
                         InstitutionDetailInfoData* institutionDetailInfo = [InstitutionDetailInfoData modelWithJSON:x];
                         
                         self.institutionData = institutionDetailInfo;
                         
                         NSLog(@"UserInfoSignal - Finish");
                         
                         [subscriber sendNext:@YES];
                         [subscriber sendCompleted];
                     }  error:^(NSError *error) {
                         //错误处理
                         
                         [subscriber sendNext:@NO];
                         [subscriber sendCompleted];
                     }];
                    
                    return nil;
                }];
    }
    else
    {
        return [RACSignal empty];
    }
}

@end
